package su.test.bidirectionalEncryption.symmetricEncryption;


import javax.crypto.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author SuZuQi
 * @title: EncrypDES
 * @projectName myEncry
 * @description: DES（Data Encryption Standard）对称加密 已经被暴力破解，现在只是用来做解密工作
 * @date 2019/12/2
 */

public class EncrypDES {

    //密钥生成器
    private static KeyGenerator keyGenerator;

    //密钥存储器
    public  static SecretKey secretKey;

    //加密工具
    private static Cipher cipher;

    private EncrypDES() {
    }

    static {
        try {
            keyGenerator = KeyGenerator.getInstance("DES");
            secretKey = keyGenerator.generateKey();
            cipher = Cipher.getInstance("DES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
    }

    public static byte[] encrypt(String text) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return cipher.doFinal(text.getBytes());
    }

    public static byte[] decrypt(byte[] bytes) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return cipher.doFinal(bytes);
    }

    public static void main(String[] args) throws BadPaddingException, InvalidKeyException, IllegalBlockSizeException, NoSuchAlgorithmException, NoSuchPaddingException {
        byte[] decrypDes = EncrypDES.encrypt("T love HuangChunYuan") ;
        KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
        SecretKey secretKey  = keyGenerator.generateKey() ;
        Cipher cipher = Cipher.getInstance("DES") ;
        cipher.init(Cipher.DECRYPT_MODE,secretKey);
        System.out.println(new String (cipher.doFinal(decrypDes)));
    }


}